package com.itheima.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.es.mapper.GoodsMapper;
import com.itheima.es.service.GoodsService;
import com.itheima.goods.pojo.Goods;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;


    private RestHighLevelClient client;

    @Override
    public void addAll () throws IOException {
        //创建Rest客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        //如果是集群，则设置多个主机，注意端口是http协议的端口
                        new HttpHost("192.168.200.151", 9200, "http")
                )
        );
        //第一步,如果索引库存在,则删除索引库
        GetIndexRequest getRequest = new GetIndexRequest("goods");
        if (client.indices().exists(getRequest, RequestOptions.DEFAULT)) {
            DeleteIndexRequest deleteRequest = new DeleteIndexRequest("goods");
            client.indices().delete(deleteRequest, RequestOptions.DEFAULT);
        }

        //第二步,创建索引库
        // 1.创建CreateIndexRequest对象，并指定索引库名称
        CreateIndexRequest request = new CreateIndexRequest("goods");
        // 2.指定mapping配置
        request.mapping(
                "{\n" +
                        "    \"properties\": {\n" +
                        "      \"id\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"name\":{\n" +
                        "        \"type\": \"text\",\n" +
                        "        \"analyzer\": \"ik_max_word\"\n" +
                        "      },\n" +
                        "      \"price\":{\n" +
                        "        \"type\": \"integer\"\n" +
                        "      },\n" +
                        "      \"num\":{\n" +
                        "        \"type\": \"integer\",\n" +
                        "        \"index\": false\n" +
                        "      },\n" +
                        "      \"image\":{\n" +
                        "        \"type\": \"keyword\",\n" +
                        "        \"index\": false\n" +
                        "      },\n" +
                        "      \"createTime\":{\n" +
                        "        \"type\": \"date\",\n" +
                        "        \"index\": false\n" +
                        "      },\n" +
                        "      \"categoryId\":{\n" +
                        "        \"type\": \"keyword\",\n" +
                        "        \"index\": false\n" +
                        "      },\n" +
                        "      \"categoryName\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"brandName\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      }\n" +
                        "    }\n" +
                        "  }",
                //指定映射的内容的类型为json
                XContentType.JSON);
        // 3.发起请求，得到响应（同步操作）
        CreateIndexResponse response = client.indices()
                .create(request, RequestOptions.DEFAULT);


        //第三步,从数据库查询文档数据
        List<Goods> goods = goodsMapper.selectList(null);

        //第四步, 批量插入到索引库中
        // 1.创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();
        // 3.创建多个IndexRequest对象，并添加到BulkRequest中
        for (Goods good : goods) {
            bulkRequest.add(new IndexRequest("goods")
                    .id(good.getId())
                    .source(JSON.toJSONString(good), XContentType.JSON)
            );
        }
        // 4.发起请求
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

}
